<?php

namespace App\Http\Models\Report;

use App\Http\Models\SalesRegion;

class InvoiceRegionContract extends SalesRegion
{
    public $cacheInvoiceRegionContracts = [];
    //年度指标
    public $target_invoice = [];
    //全年开票合计，分合同大类
    public $real_invoice_total_contract_year = [];


    public function getInvoiceMonthContractById(int $category_contract_id, int $month)
    {
        $result = 0;
        foreach ($this->cacheInvoiceRegionContracts as $value) {
            if ($value->month == $month && $value->category_contract_id == $category_contract_id) {
                $result = $value->amount;
                break;
            }
        }
        return $result;
    }

    //获取年度指标
    public function getInvoiceTargetById(int $category_contract_id)
    {
        $result = 0;
        if (array_key_exists($category_contract_id, $this->target_invoice)) {
            $result = $this->target_invoice[$category_contract_id]->amount;
        }
        return $result;
    }


    //设置年度开票合计，按合同大类分
    public function set_real_invoice_total_contract_year()
    {
        foreach ($this->cacheInvoiceRegionContracts as $value) {
            if (array_key_exists($value->category_contract_id, $this->real_invoice_total_contract_year)) {
                $this->real_invoice_total_contract_year[$value->category_contract_id] += $value->amount;
            } else {
                $this->real_invoice_total_contract_year[$value->category_contract_id] = $value->amount;
            }
        }
    }

    //获取实际年度开票数据，分合同大类
    public function getInvoiceRealYearByContract(int $category_contract_id)
    {
        $result = 0;
        if (array_key_exists($category_contract_id, $this->real_invoice_total_contract_year)) {
            $result = $this->real_invoice_total_contract_year[$category_contract_id];
        }
        return $result;
    }


    //开票进度
    public function invoiceProgress(int $category_contract_id)
    {
        $result = 0;
        $real_invoice = isset($this->real_invoice_total_contract_year[$category_contract_id]) ? $this->real_invoice_total_contract_year[$category_contract_id] : 0;
        $target_invoice = $this->getInvoiceTargetById($category_contract_id);

        if ($target_invoice != 0) {
            $result = $real_invoice / $target_invoice;
        }
        return $result;
    }


    //总开票进度
    public function invoiceProgressTotal(array $category_contract_ids)
    {
        $invoice_real = 0;
        foreach ($this->real_invoice_total_contract_year as $key => $value) {
            if (in_array($key, $category_contract_ids)) {
                $invoice_real += $value;
            }
        }

        $invoice_target = 0;

        foreach ($category_contract_ids as $value) {
            $invoice_target += $this->getInvoiceTargetById($value);
        }
        return $invoice_target != 0 ? $invoice_real / $invoice_target : 0;
    }
}
